
#import "TorrentListViewController.h"
#import "TorrentDetailsViewController.h"

@implementation TorrentListViewController

//
// torrent list
//
@synthesize torrentList														= _torrentList;

//
// page index
//
@synthesize pageIndex														= _pageIndex;

//
// page count
//
@synthesize pageCount														= _pageCount;

//
// home
//
@synthesize homeGesture														= _homeGesture;

//
// page up
//
@synthesize pageUpGesture													= _pageUpGesture;

//
// page down
//
@synthesize pageDownGesture													= _pageDownGesture;

//
// end
//
@synthesize endGesture														= _endGesture;

//
// init
//
- (id)init
{
	//
	// call super
	//
	self																	= [super initWithStyle:UITableViewStyleGrouped];
	if(!self)
		return nil;
	
	//
	// setup title,image
	//
	self.pageIndex															= 0;
	self.title																= NSLocalizedStringFromTable(@"Torrents", @"TorrentListViewController", nil);
	self.tabBarItem.image													= [UIImage imageNamed:@"tab_icon_torrent_list.png"];
	
	//
	// setup refresh,read button
	//
	self.navigationItem.rightBarButtonItem									= [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reloadTorrentList:)] autorelease];
	self.navigationItem.leftBarButtonItem									= [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedStringFromTable(@"Read", @"TorrentListViewController", nil) style:UIBarButtonItemStylePlain target:self action:@selector(markReadAll:)] autorelease];
	
	return self;
}

//
// dealloc
//
- (void)dealloc
{
	self.torrentList														= nil;
	self.homeGesture														= nil;
	self.pageUpGesture														= nil;
	self.pageDownGesture													= nil;
	self.endGesture															= nil;
	
	[super dealloc];
}

//
// reload page
//
- (void)reloadTorrentList:(id)sender
{
	NexusClient* client														= [NexusClient sharedClient];
	id getTorrentListFinished = ^void(GetTorrentListRequest* httpRequest)
	{
		[ActivityView removeView];
		if(!httpRequest.error && httpRequest.response.statusCode == 200)
		{
			self.torrentList												= httpRequest.torrentList;
			self.pageIndex													= httpRequest.pageIndex;
			self.pageCount													= httpRequest.pageCount;
			DataCenter* dataCenter											= [DataCenter sharedDataCenter];
			for(TorrentInfo* info in self.torrentList)
                [dataCenter checkAddTorrent:info];
			
			[self.tableView reloadData];
			self.title														= [NSString stringWithFormat:NSLocalizedStringFromTable(@"Page (%d/%d)", @"TorrentListViewController", nil), self.pageIndex + 1, self.pageCount];
			self.tabBarItem.title											= NSLocalizedStringFromTable(@"Torrents", @"TorrentListViewController", nil);
			
			if(!self.pageIndex)
			{
				[UIApplication sharedApplication].applicationIconBadgeNumber= 0;
				self.tabBarItem.badgeValue									= nil;
			}
		}
		else
		{
			NSString* message												= [httpRequest errorDescription];
			NSString* title													= NSLocalizedStringFromTable(@"Get Torrent List Failed", @"TorrentListViewController", nil);
			[UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"OK", nil)];
		}
	};
	[ActivityView showActivityView:NSLocalizedStringFromTable(@"Getting Torrent List", @"TorrentListViewController", nil) networking:YES];
	[client getTorrentListPage:self.pageIndex callback:getTorrentListFinished];
}

//
// loaded
//
- (void)viewDidLoad
{
	[super viewDidLoad];
	
	//
	// create guest
	//
	self.homeGesture														= [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureRecognized:)] autorelease];
	self.homeGesture.numberOfTouchesRequired								= 2;
	self.homeGesture.direction												= UISwipeGestureRecognizerDirectionLeft;
	[self.tableView addGestureRecognizer:self.homeGesture];
	self.pageUpGesture														= [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureRecognized:)] autorelease];
	self.pageUpGesture.numberOfTouchesRequired								= 1;
	self.pageUpGesture.direction											= UISwipeGestureRecognizerDirectionLeft;
	[self.tableView addGestureRecognizer:self.pageUpGesture];
	self.pageDownGesture													= [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureRecognized:)] autorelease];
	self.pageDownGesture.numberOfTouchesRequired							= 1;
	self.pageDownGesture.direction											= UISwipeGestureRecognizerDirectionRight;
	[self.tableView addGestureRecognizer:self.pageDownGesture];
	self.endGesture															= [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureRecognized:)] autorelease];
	self.endGesture.numberOfTouchesRequired									= 2;
	self.endGesture.direction												= UISwipeGestureRecognizerDirectionRight;
	[self.tableView addGestureRecognizer:self.endGesture];
	
	[self reloadTorrentList:nil];
}

//
// will appear
//
- (void)viewWillAppear:(BOOL)animated
{
	[self.tableView reloadRowsAtIndexPaths:self.tableView.indexPathsForSelectedRows withRowAnimation:UITableViewRowAnimationNone];
	[super viewWillAppear:animated];
}

//
// get section count
//
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
	return 1;
}

//
// get row count
//
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
	return self.torrentList.count;
}

//
// get cell
//
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
	TorrentListViewCell* theCell											= [tableView dequeueReusableCellWithIdentifier:@"s>"];
	if(!theCell)
		theCell																= [[[TorrentListViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"s>"] autorelease];
	
	TorrentInfo* info														= [self.torrentList objectAtIndex:indexPath.row];
	theCell.nameLabel.text													= info.title;
	theCell.timeLabel.text													= info.uploadDate;
	theCell.categoryLabel.text												= info.category;
	theCell.sizeLabel.text													= info.size;
	[theCell setupImageWithUnread:info.unread sticky:info.sticky upRate:info.upRate downRate:info.downRate];
	theCell.accessoryType													= UITableViewCellAccessoryDisclosureIndicator;
	theCell.detailTextLabel.textColor										= info.unread ? [UIColor redColor] : [UIColor grayColor];
	return theCell;
}

//
// get height
//
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
	return [TorrentListViewCell rowHeight];
}

//
// select row
//
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
	TorrentInfo* info														= [self.torrentList objectAtIndex:indexPath.row];
	if(info.unread)
	{
		[[DataCenter sharedDataCenter] markAsReadForTorrentId:info.torrentId];
		info.unread															= NO;
		[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
	}
	TorrentDetailsViewController* torrentDetailsViewController				= [[[TorrentDetailsViewController alloc] init] autorelease];
	torrentDetailsViewController.torrentInfo								= info;
	[self.navigationController pushViewController:torrentDetailsViewController animated:YES];
}

//
// read all
//
- (void)markReadAll:(id)sender
{
	NSString* title															= NSLocalizedString(@"Confirm", nil);
	NSString* message														= NSLocalizedStringFromTable(@"Mark all torrents in this page as Read?", @"TorrentListViewController", nil);
	id onDismiss = ^void(int buttonIndex)
	{
		for(TorrentInfo* info in self.torrentList)
		{
			if(info.unread)
			{
				[[DataCenter sharedDataCenter] markAsReadForTorrentId:info.torrentId];
				info.unread													= NO;
			}
		}
		
		[self.tableView reloadData];
	};
	[UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"Cancel", nil) others:[NSArray arrayWithObjects:NSLocalizedString(@"OK", nil), nil] onDismiss:onDismiss onCancel:nil];
}

//
// swipe gesture
//
- (void)swipeGestureRecognized:(UISwipeGestureRecognizer*)gesture
{
	switch(gesture.direction)
	{
	case UISwipeGestureRecognizerDirectionLeft:
		if(gesture.numberOfTouches == 1)
		{
			if(self.pageIndex)
			{
				self.pageIndex												-= 1;
				[self reloadTorrentList:nil];
			}
		}
		else if(gesture.numberOfTouches == 2)
		{
			if(self.pageIndex)
			{
				self.pageIndex												= 0;
				[self reloadTorrentList:nil];
			}
		}
		break;
		
	case UISwipeGestureRecognizerDirectionRight:
		if(gesture.numberOfTouches == 1)
		{
			if(self.pageIndex < self.pageCount - 1)
			{
				self.pageIndex												+= 1;
				[self reloadTorrentList:nil];
			}
		}
		else if(gesture.numberOfTouches == 2)
		{
			if(self.pageIndex != self.pageCount - 1)
			{
				self.pageIndex												= self.pageCount - 1;
				[self reloadTorrentList:nil];
			}
		}
		break;
		
	default:
		break;
	}
}

@end
